/**
 * New DeviceOne File
 */
var d1 = require('deviceone')
var External = d1.sm('do_External')
var Global = d1.sm('do_Global')
var Device = d1.sm('do_Device')
var log = require('util/log')
var net = require('util/net')
var server = require('config/server')
var notify = d1.sm('do_Notification')

function toastUpdate(data) {
	notify.alert({
		text : "发现了新版本，立即更新",
		title : "更新"
	}, function() {
		// TODO:更新返回状态选择
		updatePackage(data.url)
	})
}

/**
 * 下载更新包
 * 
 * @param url
 * @returns
 */
function downloadZip(url) {
	var http = mm("do_Http");
	var zip = "data://update.zip";
	http.method = "POST";
	// d.downlaodURL是zip的下载url，d.version是最新的版本号
	http.url = url;
	http.on("success", function(d) {
		update(d.version, zip);
	});
	http.download(zip);
}

/**
 * 应用完整更新
 * 
 * @returns
 */
function updatePackage(url) {
	// 测试代码
	External.openURL(url)
}

/**
 * 应用内更新
 * 
 * @returns
 */
function updateZip() {
	storage.unzip(zip, "data://update", function(data) {
		// 这里可以拷贝文件，也可以拷贝目录
		app.update([ "data://update/test.ui", "data://update/test.ui.js" ],
				"source://view", function() {
					nf.alert("升级完成");
					storage.writeFile("data://version.txt", "1.1", function() {
						app.closePage();
					});
				});
	})
}

module.exports = function() {
	var deviceOS = Device.getInfo().OS
	var version = Global.getVersion().ver
	log.info(deviceOS)
	net.send({
		server : server.appversion.checkUpdate,
		data : {
			os : deviceOS,
			version : version
		},
		success : function(data) {
			if (data && data.url) {
				toastUpdate(data)
			}
		},
		scope : this
	}, true)
}